layui.config({
    base: CXL.ctxPath + '/externaljs/'
}).extend({ //设定组件别名
    echarts: 'echarts/echarts',
    axios: 'axios/axios'
});
layui.use(['table', 'laydate', 'form', 'layer', 'element', 'echarts', 'axios'], function () {
    var oBody = document.querySelector('body')
    oBody.ondblclick = function (e) {
//        alert(e.offsetX+"========"+e.offsetY);
        //alert(e.clientX+"========"+e.clientY);
    }

    var length=0;
    var width=0;
    var thickness=0;

      $(function(){

            var active = {
                steelInfoUpdate: function(){
                    layer.open({
                        type: 1,
                        skin: 'layui-layer-rim',
                        area: ['420px', '480px'],
                        content: '<div id="steelInfoDiv4Check" style="margin-top: 50px;font-size: 30px;margin-left: 30px;">\n' +
                            '    <div><label>钢板号:</label>\n' +
                            '    <input style="width: 230px !important;" type="text" id="steelNo4Check" value="">\n' +
                            '    </div><div><label>钢板长:</label>\n' +
                            '    <input style="width: 230px !important;" type="text" id="steelLength4Check" value="'+length+'">\n' +
                            '    </div><div><label>钢板宽:</label>\n' +
                            '    <input style="width: 230px !important;" type="text" id="steelWidth4Check" value="'+width+'">\n' +
                            '    </div><div><label>钢板厚:</label>\n' +
                            '    <input style="width: 230px !important;" type="text" id="steelThick4Check" value="'+thickness+'"></div>\n' +
                            '</div>',
                        btn:'确认',
                        success: function(layero, index){
                            //console.log(layero, index);
                            let steelNo= $('#nowSteel').val();
                            layero.find('#steelNo4Check').val(steelNo);
                        },
                        yes: function(index, layero){
                            //alert(layero.find('#steelNo4Check').val());
                            let steelNo=layero.find('#steelNo4Check').val();
                            let steelLength=layero.find('#steelLength4Check').val();
                            let steelWidth=layero.find('#steelWidth4Check').val();
                            let steelThick=layero.find('#steelThick4Check').val();
                            length=parseInt(steelLength);
                            width=parseInt(steelWidth);
                            thickness=parseInt(steelThick);
                            $('#nowSteel').val(steelNo);
                            let steelNoJson = JSON.stringify(steelNo);
                            let steelLengthJson = JSON.stringify(steelLength);
                            let steelWidthJson = JSON.stringify(steelWidth);
                            let steelThickJson = JSON.stringify(steelThick);
                            let craneTypeJson = JSON.stringify(craneType);
                            let data = {
                                craneType: craneTypeJson,
                                steelNoChecked: steelNoJson,
                                steelLengthChecked: steelLengthJson,
                                steelWidthChecked: steelWidthJson,
                                steelThickChecked: steelThickJson,
                            };
                            $.ajax({
                                url: CXL.ctxPath + '/work/updateSteelInfo',
                                type: 'post',
                                data: data,
                                dataType: 'json',
                                success: function (res) {
                                    if (res.success) {
                                        CXL.success("更正成功");
                                    } else {
                                        CXL.error(res.msg);
                                    }
                                    layer.close(index);
                                },
                                fail: function () {
                                    CXL.error("网络错误！");
                                    layer.close(index);
                                }
                            });

                        }
                    });
                }
            };

            $('#steelInfoUpdate').on('click', function(){
                var type = $(this).data('type');
                active[type] && active[type].call(this);
            });

      });




    let form = layui.form;

    let craneType = "11C北";
    //初始堆放张数
    initStockNumValue(craneType);
    let stockNo="1";
    let rollerX=0;
    let stock1X=0;
    let stock2X=0;

    const xOffset = 0;
    const yOffset = 0;

    //设置图片初始路径
    const imagesUrl = CXL.ctxPath + '/baotou-steel/craneWork/images/11CNorthCrane/';
    let app = new PIXI.Application({width: 1020, height: 610});

    let plcConnectSnList = ["cdsccscdsd", "dsccsvvdvds"];

    //设置Pixi View背景颜色
    app.renderer.background.color = 0x264f7b;
    document.getElementById('craneAnimate').appendChild(app.view);

    //设置桥架container
    const bridgeContainer = new PIXI.Container();

    // 整体天车container
    const craneContainer = new PIXI.Container();
    const blockContainer = new PIXI.Container();
    const trolleyContainer = new PIXI.Container();
//加载大车小车图片
    const BlockCrane1 = PIXI.Sprite.from(imagesUrl + 'BlockCrane.png');
    const BlockCrane2 = PIXI.Sprite.from(imagesUrl + 'BlockCrane.png');
    const BlockTrolley = PIXI.Sprite.from(imagesUrl + 'BlockTrolley.png');


    //定义辊道Container
    //定义库位Container
    const rollerContainer = new PIXI.Container();
    const stockContainer = new PIXI.Container();

    //加载辊道和垛位素材
    const rollerSprite = PIXI.Sprite.from(imagesUrl + 'Roller.png');
    const stockSprite1 = PIXI.Sprite.from(imagesUrl + 'Stock.png');
    const stockSprite2 = PIXI.Sprite.from(imagesUrl + 'Stock.png');

    //渲染基准数据
    let normalRenderData = {
        BlockCrane1X: 100,
        BlockCrane1Y: 50,
        BlockCrane2X: 150,
        BlockCrane2Y: 50,

        BlockTrolleyX: 100,
        BlockTrolleyY: 220,

        upBridgeX: 25,
        upBridgeY: 50,
        downBridgeX: 25,
        downBridgeY: 550,
    }

    initPage();

    //初始化页面方法
    function initPage() {

        //绘制辊道
        drawRollers();
        //绘制垛位
        drawStocks();
        //绘制桥架
        drawBridges();
        //绘制天车
        drawCrane();

        //监听数据变化实现动画
        // new WatchValueChange(craneLocation, 'x', () => {
        //     console.log('我是监听函数')
        // })

        getRollerAndStockX(craneType);

        connect();

        //订阅任务信息
        setTimeout(function () {
            subscribeTaskStatus(craneType);
            subscribeTaskOtherStatus(craneType);
            subscribePlcData(craneType);
        }, 1000);

        setInterval(function () {
            form.render();
            //小车高度y：138      小车y：236.5   大车、小车宽度：68
            //辊道高度y：511    辊道宽度：124      辊道x：430  辊道y：50
            //垛位2宽度：198    垛位2x：700
            //(辊道X-垛位2X)/((辊道x+辊道宽度/2)-（垛位2x+垛位2宽度/2))=(辊道X-大车PLCX)/((辊道x+辊道宽度/2)-大车x)
            //let webX=(430+62)-(rollerX-no5NowXval)/((rollerX-stock2X)/((430+62)-(700+99)))

            //小车高度y：138      小车y：236.5   大车、小车宽度：68
            //辊道高度y：511    辊道宽度：124      辊道x：430  辊道y：50
            //垛位1宽度：198    垛位1x：100
            //(辊道X-垛位1X)/((辊道x+辊道宽度/2)-（垛位1x+垛位1宽度/2))=(辊道X-大车PLCX)/((辊道x+辊道宽度/2)-大车x)
            //let webX=(430+62)-(rollerX-no5NowXval)/((rollerX-stock1X)/((430+62)-(100+99)))
            let webX=0;
            if(stockNo=="1"){
                webX=(430+62)-(rollerX-nowCraneXVal)/((rollerX-stock1X)/((430+62)-(100+99)))
                webX=webX-34;
                if(webX<165){
                    webX=165;
                }
                if(webX>458){
                    webX=458;
                }
            }else{
                webX=(430+62)-(rollerX-nowCraneXVal)/((rollerX-stock2X)/((430+62)-(700+99)))
                webX=webX-34;
                if(webX<458){
                    webX=458;
                }
                if(webX>765){
                    webX=765;
                }
            }
            /*webX=webX-34;
            if(webX<128){
                webX=128;
            }
            if(webX>565){
                webX=565;
            }*/
            TweenMax.to(blockContainer, 1, { x:webX, y:50 });  //
            TweenMax.to(trolleyContainer, 1, { x:webX, y:236 });
        }, 1000)
    }

    form.on('radio(stock)', function(data){
        /*console.log(data.elem); //得到checkbox原始DOM对象
        console.log(data.elem.checked); //是否被选中，true或者false
        console.log(data.value); //复选框value值，也可以通过data.elem.value得到
        console.log(data.othis); //得到美化后的DOM对象*/
        stockNo= data.value;
    });

    function drawBridges() {
        //加载上下桥架图片
        let upBridge = PIXI.Sprite.from(CXL.ctxPath + '/baotou-steel/craneWork/images/Bridge.png');
        let downBridge = PIXI.Sprite.from(CXL.ctxPath + '/baotou-steel/craneWork/images/Bridge.png');

        upBridge.position.set(normalRenderData.upBridgeX, normalRenderData.upBridgeY);
        downBridge.position.set(normalRenderData.downBridgeX, normalRenderData.downBridgeY);

        //Container中加入桥架精灵
        bridgeContainer.addChild(upBridge);
        bridgeContainer.addChild(downBridge);

        //container加入app
        app.stage.addChild(bridgeContainer);

    }

    //绘制天车
    function drawCrane() {

        // app.stage.addChild(craneContainer);
        app.stage.addChild(blockContainer);
        app.stage.addChild(trolleyContainer);

        //设置容器相对于Pixi画布坐标
        blockContainer.position.set(100, 50);
        trolleyContainer.position.set(100, 50);

        // BlockCrane.scale.set(0.35);
        BlockCrane1.position.set(0, 0);
        // BlockCrane1.position.set(normalRenderData.BlockCrane1X, normalRenderData.BlockCrane1Y);
        BlockCrane2.position.set(50, 0);
        //缩放0.5倍
        BlockTrolley.scale.set(0.5);
        BlockTrolley.position.set(0, 0);

        blockContainer.addChild(BlockCrane1);
        blockContainer.addChild(BlockCrane2);
        trolleyContainer.addChild(BlockTrolley);

        console.log(blockContainer.x);
        console.log(blockContainer.y);
    }

    //绘制辊道
    function drawRollers() {
        app.stage.addChild(rollerContainer);
        rollerContainer.position.set(430, 20);

        rollerSprite.position.set(0, 0);
        rollerContainer.addChild(rollerSprite);
    }

    //绘制垛位
    function drawStocks() {
        app.stage.addChild(stockContainer);
        stockContainer.position.set(0, 0);

// 设置虚线样式
        stockSprite1.position.set(100, 80);
        stockSprite2.position.set(700, 80);
        stockContainer.addChild(stockSprite1);
        stockContainer.addChild(stockSprite2);

        // const text = new PIXI.Text('竖排文字', {fontSize: 24, fill: 'white'});
        drawTextVertical('一号垛位',stockSprite1,50,"#64e8fd",70,100,20);
        drawTextVertical('二号垛位',stockSprite2,50,"#64e8fd",70,100,20);

    }

    //绘制竖排文字
    /**
     *
     * @param text 文字
     * @param container 加入的容器
     * @param fontSize 字体大小
     * @param color 颜色
     * @param beginX 起始x坐标
     * @param beginY 起始y坐标
     * @param offset 两个字之间的间隔
     */
    function drawTextVertical(text, container, fontSize, color, beginX, beginY,offset) {
        Array.from(text).forEach((char) => {
            let textSprite = new PIXI.Text(char, {fontSize: fontSize, fill: color});

// 设置文本对象的位置
            textSprite.x = beginX;
            textSprite.y = beginY;

            container.addChild(textSprite);

            beginY += fontSize+offset;
        });

    }

//保存动作
    form.on('submit(startTask)', function (data) {
        //封装启动参数
        let inputDataJson = JSON.stringify(data.field);
        let craneTypeJson = JSON.stringify(craneType);
        let autoAlignNum = $("input:radio[name=autoAlign]:checked").val();
        let autoAlignFlag;
        if(autoAlignNum == '1'){
            autoAlignFlag = false;
        } else {
            autoAlignFlag = true;
        }
        let submitData = {
            craneType: craneTypeJson,
            inputData: inputDataJson,
            autoAlignFlag:autoAlignFlag,
        };


        //发送开始命令
        startWork(submitData);


    });


    //停止任务
    form.on('submit(stopTask)', function (data) {
        //封装启动参数
        let inputDataJson = JSON.stringify(data.field);
        let craneTypeJson = JSON.stringify(craneType);

        let submitData = {
            craneType: craneTypeJson,
            inputData: inputDataJson,
        };


        //发送停止命令
        stopWork(submitData);


    });

    form.on('submit(move1)', function (data) {
        //封装启动参数
        let inputDataJson = JSON.stringify(data.field);
        let craneTypeJson = JSON.stringify(craneType);

        let submitData = {
            craneType: craneTypeJson,
            inputData: inputDataJson,
        };
        //发送开始命令
        move1(submitData);
    });

    form.on('submit(suck2)', function (data) {
        //封装启动参数
        let inputDataJson = JSON.stringify(data.field);
        let craneTypeJson = JSON.stringify(craneType);

        let submitData = {
            craneType: craneTypeJson,
            inputData: inputDataJson,
        };
        //发送开始命令
        suck2(submitData);
    });

    form.on('submit(move3)', function (data) {
        //封装启动参数
        let inputDataJson = JSON.stringify(data.field);
        let craneTypeJson = JSON.stringify(craneType);

        let submitData = {
            craneType: craneTypeJson,
            inputData: inputDataJson,
        };
        //发送开始命令
        move3(submitData);
    });

    form.on('submit(place4)', function (data) {
        //封装启动参数
        let inputDataJson = JSON.stringify(data.field);
        let craneTypeJson = JSON.stringify(craneType);

        let submitData = {
            craneType: craneTypeJson,
            inputData: inputDataJson,
        };
        //发送开始命令
        place4(submitData);
    });

    form.on('checkbox(magnet)', function(data){
        /*console.log(data.elem); //得到checkbox原始DOM对象
        console.log(data.elem.checked); //是否被选中，true或者false
        console.log(data.value); //复选框value值，也可以通过data.elem.value得到
        console.log(data.othis); //得到美化后的DOM对象*/
        //封装启动参数
        let inputDataJson = JSON.stringify(data.value);
        let craneTypeJson = JSON.stringify(craneType);
        let checkedJson;
        if(data.elem.checked){
            checkedJson = JSON.stringify("true");
        }else {
            checkedJson = JSON.stringify("false");
        }
        let setMagnetData = {
            craneType: craneTypeJson,
            inputData: inputDataJson,
            isChecked:checkedJson,
        };
        //发送开始命令
        setMagnetBlock(setMagnetData);
    });

    $(function(){
        $("#stockNumberInput").change(function (){
            let value= $("#stockNumberInput").val();
            let inputDataJson = JSON.stringify(value);
            let craneTypeJson = JSON.stringify(craneType);

            let setStockNumData = {
                craneType: craneTypeJson,
                inputData: inputDataJson,
            };
            //发送开始命令
            setStockNumValue(setStockNumData);
        });

        $("#magnetValue").change(function (){
            let value= $("#magnetValue").val();
            let inputDataJson = JSON.stringify(value);
            let craneTypeJson = JSON.stringify(craneType);

            let setMagnetData = {
                craneType: craneTypeJson,
                inputData: inputDataJson,
            };
            //发送开始命令
            setMagnetValue(setMagnetData);
        });
        $("#pause").click(function(){
            let craneTypeJson = JSON.stringify(craneType);
            let data = {
                craneType: craneTypeJson,
            };
            $.ajax({
                url: CXL.ctxPath + '/work/taskPause',
                type: 'post',
                data: data,
                dataType: 'json',
                success: function (res) {
                    if (res.success) {
                        pause=true;
                        goon=false;
                    } else {
                        CXL.error(res.msg);
                    }
                },
                fail: function () {
                    CXL.error("网络错误！");
                }
            });
        });
        $("#goon").click(function(){
            let craneTypeJson = JSON.stringify(craneType);
            let data = {
                craneType: craneTypeJson,
            };
            $.ajax({
                url: CXL.ctxPath + '/work/taskGoon',
                type: 'post',
                data: data,
                dataType: 'json',
                success: function (res) {
                    if (res.success) {
                        goon=true;
                        pause=false;
                    } else {
                        CXL.error(res.msg);
                    }
                },
                fail: function () {
                    CXL.error("网络错误！");
                }
            });
        });
        $("#terminate").click(function(){
            let craneTypeJson = JSON.stringify(craneType);
            let data = {
                craneType: craneTypeJson,
            };
            $.ajax({
                url: CXL.ctxPath + '/work/taskTerminate',
                type: 'post',
                data: data,
                dataType: 'json',
                success: function (res) {
                    if (res.success) {
                        terminate=true;
                        pause=false;
                        goon=false;
                    } else {
                        CXL.error(res.msg);
                    }
                },
                fail: function () {
                    CXL.error("网络错误！");
                }
            });
        });

        $("#avoid").click(function(){
            let craneTypeJson = JSON.stringify(craneType);
            let data = {
                craneType: craneTypeJson,
            };
            layer.confirm('是否真的避让?', {icon: 3, title:'确认'}, function(index){
                $.ajax({
                    url: CXL.ctxPath + '/work/taskAvoid',
                    type: 'post',
                    data: data,
                    dataType: 'json',
                    success: function (res) {
                        if (res.success) {
                            //CXL.success("启动成功");
                        } else {
                            CXL.error(res.msg);
                        }
                    },
                    fail: function () {
                        CXL.error("网络错误！");
                    }
                });
                layer.close(index);
            });
        });

        $("#unlock").click(function(){
            let craneTypeJson = JSON.stringify(craneType);
            let data = {
                craneType: craneTypeJson,
            };
            layer.confirm('是否真的解锁辊道?', {icon: 3, title:'确认'}, function(index){
                $.ajax({
                    url: CXL.ctxPath + '/work/rollerUnlock',
                    type: 'post',
                    data: data,
                    dataType: 'json',
                    success: function (res) {
                        if (res.success) {
                            CXL.success("解锁成功");
                        } else {
                            CXL.error(res.msg);
                        }
                    },
                    fail: function () {
                        CXL.error("网络错误！");
                    }
                });
                layer.close(index);
            });
        });

    });

    function getRollerAndStockX(craneType) {
        let craneTypeJson = JSON.stringify(craneType);
        let data = {
            craneType: craneTypeJson,
        };
        $.ajax({
            url: CXL.ctxPath + '/work/getRollerAndStockX',
            type: 'post',
            data: data,
            dataType: 'json',
            success: function (res) {
                if (res.success) {
                    //console.log(res.data);
                    rollerX=res.data.rollerX;
                    stock1X=res.data.stock1X;
                    stock2X=res.data.stock2X;
                } else {
                    CXL.error(res.msg);
                }
            },
            fail: function () {
                CXL.error("网络错误！");
            }
        });
    }


    //全局方法块
    /**
     * 监听数据的改变全局方法
     * @param vm
     * @param key
     * @param action
     * @returns {*}
     * @constructor
     */
    function WatchValueChange(vm, key, action) {
        var val = vm[key]
        Object.defineProperty(vm, key, {
            enumerable: true,
            configurable: true,
            get() {
                return val
            },
            set(newVal) {
                action()
                if (val !== newVal) {
                    val = newVal
                }
            }
        })
    }

    //一键对中
    $("#align").click(function(){
        let craneTypeJson = JSON.stringify(craneType);
        let size = $("input[name='alignment']:checked").size();

        if(size <= 0){
            CXL.error('未选中对中机构，请选择合适的对中机构!');
            return;
        }
        let data = {
            craneType: craneTypeJson,
        };
        layer.confirm('是否执行一键对中?', {icon: 3, title:'确认'}, function(index){
            $.ajax({
                url: CXL.ctxPath + '/work/startAlign',
                type: 'post',
                data: data,
                dataType: 'json',
                success: function (res) {
                    if (res.success) {
                        CXL.success("启动一键对中成功");
                    } else {
                        CXL.error(res.msg);
                    }
                }
            });
            layer.close(index);
        });
    });


            form.on('submit(move1Plus)', function (data) {
                //封装启动参数
                let inputDataJson = JSON.stringify(data.field);
                let craneTypeJson = JSON.stringify(craneType);


                let submitData = {
                    craneType: craneTypeJson,
                    inputData: inputDataJson,
                };
                //发送开始命令
                move1Plus(submitData);
            });

            form.on('submit(suck2Plus)', function (data) {
                //封装启动参数
                let inputDataJson = JSON.stringify(data.field);
                let craneTypeJson = JSON.stringify(craneType);

                let submitData = {
                    craneType: craneTypeJson,
                    inputData: inputDataJson,
                };
                //发送开始命令
                suck2Plus(submitData);
            });

            form.on('submit(move3Plus)', function (data) {
                //封装启动参数
                let inputDataJson = JSON.stringify(data.field);
                let craneTypeJson = JSON.stringify(craneType);

                let submitData = {
                    craneType: craneTypeJson,
                    inputData: inputDataJson,
                };
                //发送开始命令
                move3Plus(submitData);
            });

            form.on('submit(place4Plus)', function (data) {
                //封装启动参数
                let inputDataJson = JSON.stringify(data.field);
                let craneTypeJson = JSON.stringify(craneType);

                let submitData = {
                    craneType: craneTypeJson,
                    inputData: inputDataJson,
                };
                //发送开始命令
                place4Plus(submitData);
            });


            //一键放料
            $("#easyPlace").click(function(){
                let craneTypeJson = JSON.stringify(craneType);
                let stockNo = $("input:radio[name='stock']:checked").val();
                let wideSteelFlag = $("input:radio[name='wideSteelInfo']:checked").val();
                let data = {
                    craneType: craneTypeJson,
                    stockNo:stockNo,
                    wideSteelFlag:wideSteelFlag
                };
                layer.confirm('是否执行一键放料?', {icon: 3, title:'确认'}, function(index){
                    $.ajax({
                        url: CXL.ctxPath + '/work/startEasyPlace',
                        type: 'post',
                        data: data,
                        dataType: 'json',
                        success: function (res) {
                            if (res.success) {
                                CXL.success("启动一键放料成功");
                            } else {
                                CXL.error(res.msg);
                            }
                        }
                    });
                    layer.close(index);
                });
            });


        form.on('checkbox(alignment)', function(data){
            //封装启动参数
            let inputDataJson = JSON.stringify(data.value);
            let craneTypeJson = JSON.stringify(craneType);
            let checkedJson;
            if(data.elem.checked){
                checkedJson = JSON.stringify("true");
            }else {
                checkedJson = JSON.stringify("false");
            }
            let setAlignmentData = {
                craneType: craneTypeJson,
                inputData: inputDataJson,
                isChecked:checkedJson,
            };
            //发送开始命令
            setAlignment(setAlignmentData);
        });


        function setAlignment(setAlignmentData){
            $.ajax({
                url: CXL.ctxPath + '/work/setAlignment',
                type: 'post',
                data: data,
                dataType: 'json',
                success: function (res) {
                    if (res.success) {
                        //CXL.success("启动成功。");
                    } else {
                        CXL.error(res.msg);
                    }
                },
                fail: function () {
                    CXL.error("网络错误！");
                }
            });

        };


        form.on('radio(autoAlign)', function(data){
            //封装启动参数
            let craneTypeJson = JSON.stringify(craneType);
            let checkedJson;
            let value = data.elem.value ;
            if(value == '1'){
                checkedJson = JSON.stringify("false");
            }else {
                checkedJson = JSON.stringify("true");
            }
            let setAutoAlignData = {
                craneType: craneTypeJson,
                isChecked:checkedJson,
            };
            //发送开始命令

//            setAutoAlignFlag(setAutoAlignData,value);
        });


        function setAutoAlignFlag(setAutoAlignData,value){
            $.ajax({
                url: CXL.ctxPath + '/work/setAutoAlignFlag',
                type: 'post',
                data: setAutoAlignData,
                dataType: 'json',
                success: function (res) {
                    if (res.success) {
                        //CXL.success("启动成功。");
                    } else {
                        if(value == '1'){
                            //完成页面回退
                            $("input:radio[name=autoAlign][value=2]")[0].checked = true;
//                            $("input:radio[name='autoAlign'][value='1']")[0].setAttribute('checked',false);
                        } else {
                            $("input:radio[name=autoAlign][value=1]")[0].checked = true;
                        }
                        CXL.error("操作自动对中失败！");
                    }
                },
                fail: function () {
                    CXL.error("网络错误！");
                }
            });

        };


});

